<?php

namespace Wechat\Controller;

use Think\Controller;
use OSS\OssClient;
use OSS\Core\OssException;

class CommonController extends Controller {

    protected $customer;
    protected $ossClient;

    function _initialize() {

//        cookie("openid", "otBeowu8bYi2HBRTMBWSIWzzkkbo");   //张吉煊 3
//        cookie("openid", "otBeowlAfkwtcoHunTHTDVQucZ_E");   //刘光宗 4
//        cookie("openid", "otBeowrq3-Q8-Lpkn4Q4nWnsqXBU");   //刘梓屹 757
//        cookie("openid", "otBeowt6GqmcLnxhdJkGmIVLFrzk");   //韩朋 1329
//        cookie("openid", "otBeowv0VZQORekZps57qRBc5d_0");   //安静 5
//        cookie("openid", "otBeowircpuj2wKlvqTdmz6mJd5k");   //陕西刘鹏 1682
//        cookie("openid", "otBeownKAE6D1YUDZInQmI8GzmR4");   //李建军 723
//        cookie("openid", "otBeowmiQ4VP_PP8C9Vyi5pOHIIY");   //张晨康 826
//        cookie("openid", "otBeowqZt1N7mSXkLOk4y0ejgVvY");   //赵晖 268
//        cookie("openid", "otBeownTCDmXhkAfKWaJ-_ngnhs8");   //宋汉强 610
//        cookie("openid", "otBeowuIL6V1-pFyHBbEzkuTOAz10");   //胡章 328
//        cookie("openid", "otBeowgFGSJUiavgY7EVAwd8dsqY");   //闫百栓 860


        $callback = 'http://'.$_SERVER['HTTP_HOST']
            .$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        $callback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        $str = urlencode($callback);

        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
            . C('appid') . '&redirect_uri=' . C('oauthServerUrl')
            .'&response_type=code&scope=snsapi_userinfo&state='
            . $str . '&connect_redirect=1#wechat_redirect';

        $openid = cookie("openid");

        if(isNullOrEmpty($openid)) {
            header("Location: $url");
            exit();
        }

        $currentCustomer = D("Customer")
            ->queryByMap(array("openid"=>$openid));

        if(isNullOrEmpty($currentCustomer)) {

            $currentCustomer = D("Customer")
                ->queryByMap(array("openid"=>$openid));
            if(isNullOrEmpty($currentCustomer)) {
                header("Location: $url");
                exit();
            }

            if($currentCustomer["openid"] != $openid) {
                cookie("openid", null);
                cookie("openid", $currentCustomer["openid"]);
            }

        }

        $this->customer = $currentCustomer;

        //OSS初始化
        vendor("OSS.autoload");

        $accessKeyId = C("OSS_ACCESS_KEY_ID");
        $accessKeySecret = C("OSS_ACCESS_KEY_SECRET");
        $endpoint = C("OSS_ENDPOINT");

        try {
            $this->ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false /* use cname */);
        } catch (OssException $e) {
            print $e->getMessage();
        }

        $this->ossClient->setTimeout(3600);
        $this->ossClient->setConnectTimeout(10);

    }

    /**
     * 	作用：生成签名
     */
    protected function getSign($Obj) {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    /**
     * 	作用：array转xml
     */
    protected function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml.="<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml.="<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml.="</xml>";
        return $xml;
    }

    protected function signature() {
        $Obj['jsapi_ticket'] = jsapi_ticket();
        $Obj['noncestr'] = createNoncestr();
        $Obj['url'] = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $Obj['timestamp'] = time();

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        //dump($Parameters);
        $String = formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        //$String = $String."&key=".C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = sha1($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        //$Obj['signature'] = strtoupper($String);
        $Obj['signature'] = $String;

        return $Obj;
    }

    /**
     * 	作用：产生随机字符串，不长于32位
     */
    protected function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str.= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    protected function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 	作用：将xml转为array
     */
    protected function xmlToArray($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }
//OSS上传文件
    function uploadFileToOss($filePath, $object) {
        $bucket = C('OSS_BUCKET_NAME');
        try{
            $this->ossClient->uploadFile($bucket, $object, $filePath);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        //print(__FUNCTION__ . ": OK" . "\n");
    }

    //OSS获取图片链接
    function getFileUrlFromOss($object, $isCompress = false) {

        if(!$isCompress) {
            $url = 'http://' .C('OSS_ENDPOINT_CNAME'). '/' .$object;
        } else {
            $url = 'http://' .C('OSS_IMAGE_ENDPOINT'). '/' .$object;
        }

        return $url;

    }

    //OSS分片上传
    function multiUploadFileToOss($filePath, $object, $options='') {
        $bucket = C('OSS_BUCKET_NAME');
        try{
            $this->ossClient->multiuploadFile($bucket, $object, $filePath, $options);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        //print(__FUNCTION__ . ":  OK" . "\n");

    }

    //图片缩放
    function compressImageByOss($object,$width,$height) {
        $url = 'http://' .C('OSS_IMAGE_ENDPOINT'). '/' .$object. '@' .$width. 'w_' .$height. 'h';
        return $url;
    }

    function uploadImage($imgData) {
//        return("/Template/images/arrow.png");
        $targetFolder = '/Uploads/files'; // Relative to the root
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
        if (strstr($imgData,",")){
            $imgData = explode(',',$imgData);
            $imgData = $imgData[1];
        }
        $object = md5(uniqid(mt_rand(), true)) . '.' . 'png';
        $targetFile = rtrim($targetPath, '/') . '/' . $object;
        file_put_contents($targetFile, base64_decode($imgData));
        $this->uploadFileToOss($targetFile,'image/'.$object);
        unlink($targetFile);
        return($this->getFileUrlFromOss('image/'.$object));
    }

//    function getNotifyArr($adminRoleArr, $enterpriseCode) {
//        $employeeList = D("admin")->where(array('enterprise_code'=>$enterpriseCode,'granted'=>1))->select();
//        $openidArray = array();
//        foreach ($employeeList as $singleEmployee) {
//            $roleList = explode(',', $singleEmployee["role"]);
//            foreach ($adminRoleArr as $adminRole) {
//                if (in_array($singleEmployee["openid"], $openidArray)) {
//                    continue;
//                }
//                if (in_array($adminRole,$roleList)) {
//                    array_push($openidArray, $singleEmployee["openid"]);
//                    echo($singleEmployee["openid"]."---");
//                }
//            }
//        }
//        return $openidArray;
//    }
}